#ref:
#    https://wiki.freecad.org/Sketcher_scripting
import FreeCAD as App
import Part
import Sketcher
import os

fn= u"D:/maxw/as/tmp/freecadTest/b.FCStd"
if os.path.exists(fn):
    doc = App.openDocument(fn)
    for obj in doc.Objects:
        doc.removeObject(obj.Name)
else:
    doc = App.newDocument()
    doc.saveAs(fn)
    print(f"新建并保存文件: {fn}")

sketch = doc.addObject("Sketcher::SketchObject", "Sketch")
sketch.addGeometry(Part.LineSegment(App.Vector(1.2, 1.8, 0), App.Vector(5.2, 5.3, 0)), False) #idx:0
sketch.addGeometry(Part.LineSegment(App.Vector(6.5, 1.5, 0), App.Vector(10.2, 5.0, 0)), False) #idx:1 最后一个参数貌似是是否隐藏？  http://localhost:7465/Part.html#LineSegment  文档中也没说必须。。。
sketch.addGeometry(Part.LineSegment(App.Vector(12.2, 1.0, 0), App.Vector(15.4, 5.0, 0)), False) #idx:2

#geometric constraint
#sketch.addConstraint(Sketcher.Constraint(ConstraintType, EdgeOrPartOfEdge…))

#dimensional constraint
#sketch.addConstraint(Sketcher.Constraint(DimensionalConstraintType, EdgeOrPartOfEdge…, App.Units.Quantity("float_value unit")))

#给圆添加半径约束
#App.getDocument('Unnamed').getObject('Sketch').addConstraint(Sketcher.Constraint('Radius',0,45.000000))
#App.getDocument('Unnamed').getObject('Sketch').setDatum(1,App.Units.Quantity('42.000000 mm')) #这里的参数1为 上一行添加约束的返回值，代表那个约束，句柄
#给圆添加直径约束
#App.getDocument('Unnamed').getObject('Sketch').addConstraint(Sketcher.Constraint('Diameter',0,90.0))
#App.getDocument('Unnamed').getObject('Sketch').setDatum(1,App.Units.Quantity('90.000000 mm'))

sketch.addConstraint(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) #一致约束  基点：第1条线的第2个端点  调整点：第2条线的第1个端点
doc.recompute()
doc.save()